package com.tang.controller;


import com.tang.pojo.User;
import com.tang.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
/**
 * @Author Tom
 * @ClassName LoginController
 * @Date 2021/10/29 22:26
 */
@Controller
@RequestMapping("/userSystem")
public class LoginController {

    private UserService userService;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/login")
    public String verify(String username, String password, Model model, HttpServletRequest request) throws UnsupportedEncodingException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        //获取用户填写验证码
        String checkCode = request.getParameter("checkCode");
        //验证码校验
        HttpSession session = request.getSession();
        String checkCode_server = (String) session.getAttribute("checkCode_server");
        if (checkCode != null) {
            if (!checkCode_server.equalsIgnoreCase(checkCode)) { //服务器端生成的验证码不等于用户填写的验证码
                //验证码不正确,提示信息
                model.addAttribute("msg", "验证码错误");
                session.removeAttribute("checkCode_server");//确保验证码一次性
                return "login";
            }
        }
        User user = userService.findUser(username, password);
        if (user != null) {
            String username1 = user.getUsername();
            session.setAttribute("user", user);
//            model.addAttribute("msg","登录成功，欢迎您"+username1);
            return "redirect:/admin/queryAll?currentPage=1";
        } else {
            model.addAttribute("msg", "用户名或密码错误");
            return "login";
        }

    }

}
